<template>
  <div class="student-management-container">
    <div class="header">
      <h2>学生管理</h2>
      <el-button type="primary" @click="showAddDialog = true">添加学生</el-button>
    </div>

    <el-card>
      <el-form :inline="true" class="filter-form">
        <el-form-item label="姓名">
          <el-input v-model="filters.name" placeholder="学生姓名" clearable />
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="filters.studentId" placeholder="学号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="filterStudents">筛选</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="filteredStudents" style="width: 100%">
        <el-table-column prop="realName" label="姓名" width="120" />
        <el-table-column prop="username" label="学号" width="150" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="department" label="院系" />
        <el-table-column label="添加时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button link type="primary" @click="viewStudent(scope.row)">查看</el-button>
            <el-button link type="primary" @click="editStudent(scope.row)">编辑</el-button>
            <el-button link type="danger" @click="deleteStudent(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          :total="filteredStudents.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑学生对话框 -->
    <el-dialog 
      v-model="showAddDialog" 
      :title="isEdit ? '编辑学生' : '添加学生'" 
      width="50%"
    >
      <el-form 
        :model="studentForm" 
        label-width="120px" 
        :rules="rules" 
        ref="formRef"
      >
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="studentForm.realName" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="学号" prop="username">
          <el-input v-model="studentForm.username" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="studentForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="院系" prop="department">
          <el-select v-model="studentForm.department" placeholder="请选择院系" style="width: 100%">
            <el-option label="计算机科学学院" value="计算机科学学院" />
            <el-option label="机械工程学院" value="机械工程学院" />
            <el-option label="电子工程学院" value="电子工程学院" />
            <el-option label="经济管理学院" value="经济管理学院" />
            <el-option label="理学院" value="理学院" />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="studentForm.password" type="password" placeholder="请输入初始密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="!isEdit">
          <el-input v-model="studentForm.confirmPassword" type="password" placeholder="请确认密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="submitStudentForm" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看学生详情对话框 -->
    <el-dialog v-model="showViewDialog" title="学生详情" width="50%">
      <div class="student-detail" v-if="currentStudent">
        <div class="detail-item">
          <span class="label">姓名：</span>
          <span class="value">{{ currentStudent.realName }}</span>
        </div>
        <div class="detail-item">
          <span class="label">学号：</span>
          <span class="value">{{ currentStudent.username }}</span>
        </div>
        <div class="detail-item">
          <span class="label">邮箱：</span>
          <span class="value">{{ currentStudent.email }}</span>
        </div>
        <div class="detail-item">
          <span class="label">院系：</span>
          <span class="value">{{ currentStudent.department }}</span>
        </div>
        <div class="detail-item">
          <span class="label">添加时间：</span>
          <span class="value">{{ formatDate(currentStudent.createdAt) }}</span>
        </div>
        
        <el-divider content-position="left">成果统计</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="statistic-card">
              <div class="statistic-title">总成果数</div>
              <div class="statistic-value">{{ currentStudent.stats?.total || 0 }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="statistic-card">
              <div class="statistic-title">已通过</div>
              <div class="statistic-value">{{ currentStudent.stats?.approved || 0 }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="statistic-card">
              <div class="statistic-title">待审核</div>
              <div class="statistic-value">{{ currentStudent.stats?.pending || 0 }}</div>
            </div>
          </el-col>
        </el-row>
        
        <el-button 
          type="primary" 
          class="view-achievements-btn"
          @click="viewStudentAchievements"
        >查看该学生的所有成果</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, computed } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import TeacherService from '@/api/teacher'

interface StudentStats {
  total: number
  approved: number
  pending: number
}

interface Student {
  id: number
  username: string
  realName: string
  email: string
  department: string
  createdAt: string
  stats?: StudentStats
}

export default defineComponent({
  name: 'StudentManagement',
  setup() {
    const router = useRouter()
    const loading = ref(true)
    const students = ref<Student[]>([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const showAddDialog = ref(false)
    const showViewDialog = ref(false)
    const isEdit = ref(false)
    const currentStudent = ref<Student | null>(null)
    const formRef = ref<FormInstance>()
    const submitting = ref(false)

    const filters = reactive({
      name: '',
      studentId: ''
    })

    const studentForm = reactive({
      id: 0,
      realName: '',
      username: '',
      email: '',
      department: '',
      password: '',
      confirmPassword: ''
    })

    const rules = {
      realName: [
        { required: true, message: '请输入学生姓名', trigger: 'blur' }
      ],
      username: [
        { required: true, message: '请输入学号', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      department: [
        { required: true, message: '请选择院系', trigger: 'change' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
          validator: (rule: any, value: string, callback: (error?: Error) => void) => {
            if (value !== studentForm.password) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    const filteredStudents = computed(() => {
      let result = [...students.value]
      
      if (filters.name) {
        result = result.filter(student => 
          student.realName.toLowerCase().includes(filters.name.toLowerCase())
        )
      }
      
      if (filters.studentId) {
        result = result.filter(student => 
          student.username.toLowerCase().includes(filters.studentId.toLowerCase())
        )
      }
      
      return result
    })

    const fetchStudents = async () => {
      loading.value = true
      try {
        const response = await TeacherService.getMyStudents()
        students.value = response.data
        total.value = response.data.length
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '获取学生列表失败')
      } finally {
        loading.value = false
      }
    }

    const filterStudents = () => {
      // 前端过滤，不需要再调用API
    }

    const resetFilters = () => {
      filters.name = ''
      filters.studentId = ''
    }

    const handleSizeChange = (val: number) => {
      pageSize.value = val
    }

    const handleCurrentChange = (val: number) => {
      currentPage.value = val
    }

    const formatDate = (dateString: string) => {
      if (!dateString) return ''
      
      // 转换ISO格式日期为更友好的格式
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const viewStudent = (student: Student) => {
      // 获取学生统计数据，目前使用模拟数据
      const studentWithStats = {
        ...student,
        stats: {
          total: 8,
          approved: 5,
          pending: 3
        }
      }
      currentStudent.value = studentWithStats
      showViewDialog.value = true
    }

    const editStudent = (student: Student) => {
      isEdit.value = true
      studentForm.id = student.id
      studentForm.realName = student.realName
      studentForm.username = student.username
      studentForm.email = student.email
      studentForm.department = student.department
      studentForm.password = ''
      studentForm.confirmPassword = ''
      showAddDialog.value = true
    }

    const deleteStudent = (student: Student) => {
      ElMessageBox.confirm(
        `确定要删除学生 ${student.realName} 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await TeacherService.deleteStudent(student.id)
          ElMessage.success('删除成功')
          fetchStudents()
        } catch (error: any) {
          ElMessage.error(error.response?.data?.message || '删除失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }

    const resetForm = () => {
      studentForm.id = 0
      studentForm.realName = ''
      studentForm.username = ''
      studentForm.email = ''
      studentForm.department = ''
      studentForm.password = ''
      studentForm.confirmPassword = ''
    }

    const submitStudentForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            if (isEdit.value) {
              // 调用更新API
              await TeacherService.updateStudent({
                id: studentForm.id,
                realName: studentForm.realName,
                email: studentForm.email,
                department: studentForm.department
              })
              ElMessage.success('编辑成功')
            } else {
              // 调用创建API
              await TeacherService.addStudent({
                username: studentForm.username,
                password: studentForm.password,
                realName: studentForm.realName,
                email: studentForm.email,
                department: studentForm.department
              })
              ElMessage.success('添加成功')
            }
            
            showAddDialog.value = false
            resetForm()
            fetchStudents() // 刷新学生列表
          } catch (error: any) {
            ElMessage.error(error.response?.data?.message || (isEdit.value ? '编辑失败' : '添加失败'))
          } finally {
            submitting.value = false
          }
        }
      })
    }

    const viewStudentAchievements = () => {
      if (!currentStudent.value) return
      
      // 跳转到成果列表并过滤该学生的成果
      router.push({
        path: '/teacher/achievements',
        query: { studentId: currentStudent.value.id.toString() }
      })
      showViewDialog.value = false
    }

    onMounted(() => {
      fetchStudents()
    })

    return {
      loading,
      students,
      filteredStudents,
      total,
      currentPage,
      pageSize,
      filters,
      showAddDialog,
      showViewDialog,
      isEdit,
      currentStudent,
      studentForm,
      formRef,
      rules,
      submitting,
      filterStudents,
      resetFilters,
      handleSizeChange,
      handleCurrentChange,
      formatDate,
      viewStudent,
      editStudent,
      deleteStudent,
      submitStudentForm,
      viewStudentAchievements
    }
  }
})
</script>

<style scoped>
.student-management-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.filter-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.student-detail {
  padding: 10px;
}

.detail-item {
  margin-bottom: 15px;
}

.label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
}

.statistic-card {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  text-align: center;
  margin-bottom: 20px;
}

.statistic-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.statistic-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.view-achievements-btn {
  margin-top: 20px;
  width: 100%;
}
</style> 